/*
 * @lc app=leetcode.cn id=605 lang=rust
 *
 * [605] 种花问题
 */

// @lc code=start
impl Solution {
    pub fn can_place_flowers(flowerbed: Vec<i32>, n: i32) -> bool {
        let mut flowerbed = flowerbed;
        
        if n == 0 { return true; }
        if n > (flowerbed.len() as i32) / 2 + 1{
            return false;
        }

        if flowerbed.len() == 1{
            if flowerbed[0] == 0 { return true; }
        }
        
        //此时有n > 0, n <= (flowerbed.len() as i32) / 2, flowerbed.len() > 1
        let mut count = 0;
        if flowerbed[0] == 0 && flowerbed[1] == 0{ 
            count = 1;
            flowerbed[0] = 1;
        }

        let len = flowerbed.len();
        //为了方便计算，在最后面加上01不影响结果。
        flowerbed.push(0);
        flowerbed.push(1);

        let mut i = 2;//此时有flowerbed[0] == 1
        while i < len{
            if flowerbed[i] + flowerbed[i-1] + flowerbed[i+1] == 0{
                flowerbed[i] = 1;
                count += 1;
                i += 2;
            }
            else{
                i += 1;
            }
        }

        return count >= n;
        
    }
}
// @lc code=end

